import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { messageApi } from '@/api/message'
import { userApi } from '@/api/user'
import { useAuthStore } from '@/stores/auth'
import { Client } from '@stomp/stompjs'
import SockJS from 'sockjs-client'

let stompClient = null;

export const useChatStore = defineStore('chat', () => {
  const messages = ref([])
  const users = ref([])
  const currentChatUser = ref(null)
  const unreadCount = ref(0)

  const currentUser = computed(() => {
    const authStore = useAuthStore()
    return authStore.user
  })

  const loadUsers = async () => {
    try {
      const response = await userApi.getAllUsers()
      console.log('API返回的用户列表:', response.data.data)
      // 过滤掉当前用户自己
      const filteredUsers = response.data.data.filter(user => user.id !== currentUser.value.id)
      console.log('过滤后的用户列表:', filteredUsers)
      users.value = filteredUsers
    } catch (error) {
      console.error('加载用户列表失败:', error)
    }
  }

  const loadMessages = async (otherUserId, page = 0, size = 20) => {
    try {
      const response = await messageApi.getChatMessages(otherUserId, page, size)
      const newMessages = response.data.data.content || response.data.data
      
      console.log('loadMessages - 原始消息列表 (来自API):', JSON.parse(JSON.stringify(newMessages))); // 打印原始消息，深拷贝以避免后续修改影响

      // 处理撤回消息的显示文本
      newMessages.forEach(message => {
        if (message.isRecalled) {
          if (message.sender.id === currentUser.value.id) {
            message.content = '您撤回了一条消息';
          } else {
            message.content = `${message.sender.nickname || message.sender.username} 撤回了一条消息`;
          }
        }
      });

      console.log('loadMessages - 处理撤回消息后的列表:', JSON.parse(JSON.stringify(newMessages))); // 打印处理后的消息

      // 确保消息按时间升序排列 (从旧到新)
      const sortedNewMessages = newMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
      console.log('loadMessages - 排序后消息列表:', JSON.parse(JSON.stringify(sortedNewMessages))); // 打印排序后消息

      if (page === 0) {
        messages.value = sortedNewMessages
      } else {
        // 当加载更多旧消息时，将它们添加到现有消息的前面，并重新排序整个列表
        const combinedMessages = [...sortedNewMessages, ...messages.value];
        const finalSortedMessages = combinedMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
        messages.value = finalSortedMessages;
        console.log('loadMessages - 合并并最终排序后消息列表 (加载更多):', JSON.parse(JSON.stringify(messages.value)));
      }
      console.log('loadMessages - 最终赋值给 messages.value 的列表:', JSON.parse(JSON.stringify(messages.value)));

    } catch (error) {
      console.error('加载消息失败:', error)
    }
  }

  const sendMessage = async (content, receiverId, messageType = 'TEXT', fileUrl = null, fileName = null, fileSize = null) => {
    if (stompClient && stompClient.connected) {
      const message = {
        content,
        receiverId,
        messageType,
        fileUrl,
        fileName,
        fileSize,
        sender: currentUser.value // 添加发送者信息
      };
      // 直接通过WebSocket发送消息
      stompClient.publish({
        destination: '/app/chat.sendMessage',
        body: JSON.stringify(message)
      });
      // 本地添加消息以实现即时显示
      messages.value.push({
        ...message,
        sender: currentUser.value,
        id: Date.now(), // 临时ID，实际ID会由后端返回
        createdAt: new Date().toISOString(),
        isRead: false,
        isRecalled: false,
      });
      return { success: true };
    } else {
      // 如果WebSocket未连接，则回退到HTTP发送（可选）
      try {
        const response = await messageApi.sendMessage({
          content,
          receiverId,
          messageType,
          fileUrl,
          fileName,
          fileSize
        });
        const newMessage = response.data.data;
        messages.value.push(newMessage);
        return { success: true, message: newMessage };
      } catch (error) {
        return {
          success: false,
          message: error.response?.data?.message || '发送失败'
        };
      }
    }
  };

  const recallMessage = async (messageId) => {
    if (stompClient && stompClient.connected) {
      stompClient.publish({
        destination: '/app/chat.recallMessage',
        body: JSON.stringify({ messageId })
      });
      // 本地更新消息状态
      const messageIndex = messages.value.findIndex(msg => msg.id === messageId);
      if (messageIndex !== -1) {
        messages.value[messageIndex].isRecalled = true;
        messages.value[messageIndex].content = '您撤回了一条消息';
        console.log(`本地消息撤回成功: Message ID: ${messageId}, isRecalled: ${messages.value[messageIndex].isRecalled}, Content: ${messages.value[messageIndex].content}`);
      }
      return { success: true };
    } else {
      // 回退到HTTP撤回
      try {
        await messageApi.recallMessage(messageId);
        const messageIndex = messages.value.findIndex(msg => msg.id === messageId);
        if (messageIndex !== -1) {
          messages.value[messageIndex].isRecalled = true;
          messages.value[messageIndex].content = '您撤回了一条消息';
          console.log(`HTTP撤回成功: Message ID: ${messageId}, isRecalled: ${messages.value[messageIndex].isRecalled}, Content: ${messages.value[messageIndex].content}`);
        }
        return { success: true };
      } catch (error) {
        return {
          success: false,
          message: error.response?.data?.message || '撤回失败'
        };
      }
    }
  };

  const markAsRead = async (messageId) => {
    try {
      await messageApi.markAsRead(messageId)
      
      const messageIndex = messages.value.findIndex(msg => msg.id === messageId)
      if (messageIndex !== -1) {
        messages.value[messageIndex].isRead = true
      }
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }

  const addMessage = (message) => {
    // 检查是否已存在该消息
    const exists = messages.value.some(msg => msg.id === message.id)
    if (!exists) {
      messages.value.push(message)
    }
  }

  const updateMessage = (messageId, updates) => {
    const messageIndex = messages.value.findIndex(msg => msg.id === messageId)
    if (messageIndex !== -1) {
      messages.value[messageIndex] = { ...messages.value[messageIndex], ...updates }
    }
  }

  const setCurrentChatUser = (user) => {
    currentChatUser.value = user
    console.log('Current chat user set to:', currentChatUser.value);
  }

  const clearMessages = () => {
    messages.value = []
  }

  // WebSocket相关逻辑
  const connectWebSocket = () => {
    if (stompClient && stompClient.connected) {
      return;
    }

    // 使用SockJS作为WebSocket的回退方案
    stompClient = new Client({
      webSocketFactory: () => {
        return new SockJS('http://localhost:8080/api/ws'); // 后端WebSocket端点
      },
      debug: (str) => {
        console.log('STOMP Debug:', str);
      },
      reconnectDelay: 5000, // 5秒后尝试重新连接
      heartbeatIncoming: 4000, // 后端心跳间隔
      heartbeatOutgoing: 4000, // 前端心跳间隔

      // 连接头，用于传递JWT令牌或用户名
      connectHeaders: {
        // 假设您的后端需要Authorization头
        // 'Authorization': `Bearer ${authStore.token}`,
        'username': currentUser.value?.username // 传递当前用户名用于身份验证
      },
    });

    stompClient.onConnect = (frame) => {
      console.log('STOMP WebSocket连接成功:', frame);
      // 订阅公共状态更新主题
      stompClient.subscribe('/topic/public/status', (message) => {
        const statusUpdate = JSON.parse(message.body);
        console.log('接收到状态更新:', statusUpdate);
        const updatedUser = statusUpdate;
        const userIndex = users.value.findIndex(u => u.id === updatedUser.userId);
        if (userIndex !== -1) {
          // 使用onlineStatus字段而不是根据type判断
          if (updatedUser.onlineStatus) {
            users.value[userIndex].onlineStatus = updatedUser.onlineStatus;
          } else {
            // 兼容旧版本，根据type判断
            users.value[userIndex].onlineStatus = updatedUser.type === 'USER_ACTIVE' ? 'ONLINE' : 'OFFLINE';
          }
          if (updatedUser.lastLoginAt) {
            users.value[userIndex].lastLoginAt = updatedUser.lastLoginAt;
          }
        } else {
          // 如果是新用户上线，可以考虑重新加载用户列表或添加到列表
          loadUsers(); 
        }
      });

      // 订阅点对点消息 (例如：新消息, 消息撤回通知)
      stompClient.subscribe(`/user/${currentUser.value?.username}/queue/messages`, (message) => {
        const receivedMessage = JSON.parse(message.body);
        console.log('Received private message:', receivedMessage);
        // 在这里处理接收到的消息，例如添加到messages数组
        if (receivedMessage.messageType === 'RECALL') {
          const recalledMessageId = receivedMessage.messageId;
          const messageIndex = messages.value.findIndex(msg => msg.id === recalledMessageId);
          if (messageIndex !== -1) {
            const originalMessage = messages.value[messageIndex];
            originalMessage.isRecalled = true;
            // 根据发送者判断显示不同的提示文本
            let newContent = '';
            // 检查 receivedMessage 中是否包含 senderId，因为原始消息可能不在本地消息列表中
            // 更可靠的判断是使用 receivedMessage.senderId 和 currentUser.value.id
            if (receivedMessage.senderId === currentUser.value.id) {
              newContent = '您撤回了一条消息';
            } else {
              newContent = `${receivedMessage.senderNickname || receivedMessage.senderUsername} 撤回了一条消息`;
            }
            originalMessage.content = newContent;
            console.log(`WebSocket撤回通知处理成功: Message ID: ${recalledMessageId}, isRecalled: ${originalMessage.isRecalled}, Content: ${originalMessage.content}`);
          }
        } else {
          // Handle other message types (e.g., TEXT, FILE)
          if (currentChatUser.value &&
              (receivedMessage.sender.id === currentChatUser.value.id || receivedMessage.receiverId === currentChatUser.value.id)
          ) {
            addMessage(receivedMessage);
          }
        }
      });

      // 通知后端用户上线，发送一个JOIN消息
      stompClient.publish({
        destination: '/app/chat.addUser',
        body: JSON.stringify({ sender: currentUser.value?.username })
      });
    };

    stompClient.onStompError = (frame) => {
      console.error('STOMP Error:', frame);
    };

    stompClient.onWebSocketError = (event) => {
      console.error('WebSocket Error:', event);
    };

    stompClient.onDisconnect = (frame) => {
      console.log('STOMP WebSocket断开连接:', frame);
    };
    
    stompClient.activate();
  };

  const disconnectWebSocket = () => {
    if (stompClient && stompClient.connected) {
      stompClient.deactivate();
      stompClient = null;
      console.log('STOMP WebSocket已断开');
    }
  };

  return {
    messages,
    users,
    currentChatUser,
    unreadCount,
    currentUser,
    loadUsers,
    loadMessages,
    sendMessage,
    recallMessage,
    markAsRead,
    addMessage,
    updateMessage,
    setCurrentChatUser,
    clearMessages,
    connectWebSocket,
    disconnectWebSocket
  }
}) 